import React from 'react';
import { Spin } from 'antd';
import {formatDate, openLinkUrl} from '../../util/common';
import { isEqual, isEmpty, cloneDeep } from 'lodash';
import {WeaTools, WeaErrorPage, WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
const { ls } = WeaTools;

import EHeader from '../common/EHeader';
import EContent from './EContent';
import { NoRightCom, handleHeight } from '../../util/common';
import FooterMore from "../common/FooterMore";
//元素组件
class News extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            edata: null,
            refresh: false,
            color: '#939393',
            canEdit: false
        }
        this.handleEData = this.handleEData.bind(this);
        this.handleRefresh = this.handleRefresh.bind(this);
        this.handleDelete = this.handleDelete.bind(this);
        this.handleOpen = this.handleOpen.bind(this);
        this.onChangeCanEdit = this.onChangeCanEdit.bind(this);
        this.onRef = this.onRef.bind(this);
        this.handleTabData = this.handleTabData.bind(this);
    }
    handleDelete(){
        this.setState({
            edata: null,
        });
        ls.set('edata-'+this.props.config.params.eid, null);
    }

    handleRefresh(){
        this.setState({
            refresh: true,
        });
        this.handleEData(this.props.config.params);
    }
    handleEData(params){
        let { edata={}} = this.state;
        if (edata == null) edata ={};
        const { currenttab='1'} = edata
        const { eid, api } = params;
        ls.set('portal-doc-right', null);
        WeaTools.callApi(api || '/api/portal/element/news', 'POST', {...params}).then(result=> {
            const edata_local = ls.getJSONObj('edata-'+eid);
            if(edata_local != null) {
                const { data={} } = edata_local;
                const { data: data1={} } = result;
                const { docParams={} } = data;
                const { docParams: docParams1={} } = data1;
                const { docCatalogIds =[] } = docParams;
                const { docCatalogIds: docCatalogIds1 =[] } = docParams1;
                const _self = this;
                let paramsNew = {ids: docCatalogIds1.join()};
                let rightArr = ls.getJSONObj('portal-doc-right');
                if(rightArr == null){
                    if(!this.isTrue){
                        this.isTrue = true;
                        WeaTools.callApi('/api/portal/elementsetdoc/docsetright', 'POST', paramsNew).then(result => {
                            let right = result.canEdit == 'true' ? true : false ;
                            this.onChangeCanEdit(right);
                            ls.set('portal-doc-right', [{eid: eid, tabid: currenttab, data: formatDate(new Date(), "yyyy-MM-dd"),right: right}]);
                            _self.isTrue = false;
                        });
                    }
                }else{
                    let isHave = false;

                    WeaTools.callApi('/api/portal/elementsetdoc/docsetright', 'POST', paramsNew).then(result => {
                        let right = result.canEdit == 'true' ? true : false ;
                        rightArr = rightArr.map((item)=>{
                            if(item == null){
                                return item;
                            }else if(item.eid == eid && item.tabid == currenttab){
                                isHave = true;
                                item.right = right;
                            }
                            return item;
                        });
                        _self.onChangeCanEdit(right);
                        ls.set('portal-doc-right', rightArr);
                        if(!isHave){
                            WeaTools.callApi('/api/portal/elementsetdoc/docsetright', 'POST', paramsNew).then(result => {
                                let right = result.canEdit == 'true' ? true : false ;
                                _self.onChangeCanEdit(right);
                                rightArr.push({eid: eid, tabid: currenttab,data: formatDate(new Date(), "yyyy-MM-dd"), right: right });
                                ls.set('portal-doc-right', rightArr);
                            });
                        }
                    });
                }
            }
            ls.set('edata-'+eid, result);
            this.setState({
                edata: result,
                refresh: false,
            });
        });
    }
    handleOpen(){
        const { edata } = this.state;
        const { data = {} } = edata;
        const { tabsetting = {} } = data;
        const { catalogId, catalogIds } = tabsetting;
        if(catalogId){
            openLinkUrl('/spa/document/index.jsp?secid='+catalogId+'&isEdit=1&moudleFrom=portal','2');
        }else{
            openLinkUrl('/spa/document/static/index.html#/main/document/add?openNewWindow=0&moudleFrom=portal&secids='+catalogIds,'2');
        }
    }
    onChangeCanEdit(value){
        this.setState({
            canEdit: value
        })
    }
    componentDidMount(){
        const { config = {} } = this.props;
        const { params = {} } = config;
        const { eid } = params;
        const edata = ls.getJSONObj(`edata-${eid}`);
        if (config.islsdata && edata) {
            this.setState({ edata });
        } else {
            this.handleEData(params);
        }
    }
    componentWillReceiveProps(nextProps){
        const { item, params, isHasRight } = this.props.config;
        const config = { item, params, isHasRight };
        const _config = {
            item: nextProps.config.item,
            params: nextProps.config.params,
            isHasRight: nextProps.config.isHasRight,
        };
        if(!isEqual(config, _config) || nextProps.config.isRender){
            this.handleEData(nextProps.config.params);
        }
    }
    shouldComponentUpdate(nextProps, nextState){
        const { item, params, isHasRight } = this.props.config;
        const config = { item, params, isHasRight };
        const _config = {
            item: nextProps.config.item,
            params: nextProps.config.params,
            isHasRight: nextProps.config.isHasRight,
        };
        return !isEqual(this.state, nextState) || !isEqual(config, _config) || !isEmpty(nextProps.fontSizeMp)
    }
    onRef(ref){
        this.child = ref;
    }

    handleTabData(tabid){
        this.child.handleTabData(tabid)
    }

    render() {
        const { edata={}, refresh } = this.state;
        const { config, fontSizeMp } = this.props;
        if(!config || !edata) return <div/>;
        const { currenttab='1', tabids, titles, esetting={}, counts, data = {} } = edata
        const { tabsetting = {} } = data;
        const { isHasRight, item } = config;
        const { eid, ebaseid, content, header, contentview, style } = item;
        const { style: style1= {} } = contentview;
        const datas = {
            currentTab: this.child && this.child.state.currentTab ? this.child.state.currentTab:currenttab,
            tabids,
            titles,
            counts,
            isShowSettingShowType: tabsetting.isShowSettingShowType,
            handleTabData: this.handleTabData,
            tabwidth: esetting.tabwidth,
            methodvalue: esetting.methodvalue,
            tabstyle: esetting.tabstyle,
            tabvalue: esetting.tabvalue,
            isAlwaysShow: esetting.isAlwaysShow
        }
        let edata_img = {data: {}};
        if(!isEmpty(edata) && isHasRight){
            edata_img = cloneDeep(edata);
            if(edata_img.data && edata_img.data.tabsetting) edata_img.data.tabsetting.imgs=[];
        }
        let EContentHtml = <div/>;
        if(isHasRight){
            if(!isEmpty(edata)) EContentHtml = <EContent ecId={`${this && this.props && this.props.ecId || ''}_EContent@zb57dx`} onRef={this.onRef} config={config} ref={"eContent"} fontSizeMp={fontSizeMp} handleDelete={this.handleDelete} handleRefresh={this.handleRefresh} edata={!refresh ? edata: edata_img} onChangeCanEdit={this.onChangeCanEdit}/>;
        }else{
            EContentHtml = <NoRightCom ecId={`${this && this.props && this.props.ecId || ''}_NoRightCom@u8b5xp`}/>
        }
        return <div className="item"
                    style={style}
                    id={`item_${eid}`}
                    data-eid={eid} data-ebaseid={ebaseid}
                    data-needRefresh={item.needRefresh}
                    data-cornerTop={item.cornerTop}
                    data-cornerTopRadian={item.cornerTopRadian}
                    data-cornerBottom={item.cornerBottom}
                    data-cornerBottomRadian={item.cornerBottomRadian}>
            <EHeader ecId={`${this && this.props && this.props.ecId || ''}_EHeader@r1mcg3`} datas={datas} config={config} handleRefresh={this.handleRefresh} handleDelete={this.handleDelete} fontSizeM={fontSizeMp}/>
            <div className="setting" id={`setting_${eid}`}></div>
            <div className="content portal-news-img-content" id={`content_${eid}`} style={{width:'auto',height:'100%'}}>
                <div style={{width:'auto',height:'100%', position: 'relative'}}>
                    {this.state.canEdit && <div title='新建文档' style={{right: '30px', bottom: '20px', position: 'absolute'}} className={'portal-element-news-doc-add-icon'}  onClick={() => {
                        this.refs && this.refs.eContent.handleOpen()
                    }} style={{color: this.state.color}}><img src='/spa/portal/images/news_add.png' alt='' /></div>}
                    {
                        edata.tabids && edata.tabids.length > 1 ? <div className="content_view" id={`content_view_id_${eid}`} style={{height: style1.height}}>
                                <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@t1thbw`} spinning={refresh}>{EContentHtml}</Spin>
                            </div>:
                            <div className="content_view" id={`content_view_id_${eid}`} style={{height: style1.height}}>
                                <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@02z4xv`} spinning={refresh}>{EContentHtml}</Spin>
                            </div>
                    }
                    <div style = {{textAlign:'right'}} id={`footer_${eid}`}>
                        <FooterMore ecId={`${this && this.props && this.props.ecId || ''}_FooterMore@ca316g`} config={this.props.config}/>
                    </div>
                </div>
            </div>
        </div>;
    }
}

class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
        return ( <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@xahx62`} msg = { hasErrorMsg ? this.props.error :  getLabel(385218,"对不起，该页面异常，请联系管理员！") }/>
        );
    }
}
News = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(News);
export default News;



